#include <QString>
#include <QtGui>
#include <QtDebug>

#include "generateid.h"
#include "insertdatawidget.h"

InsertDataWidget::InsertDataWidget( QString table, QWidget * parent) 
	:QWidget(parent)
{
	setupUi(this);
	this->table = table;
	model = new QSqlTableModel(this);

	connect(addButton,SIGNAL(clicked()),this,SLOT(addRow()));
	connect(removeButton,SIGNAL(clicked()),this,SLOT(delRow()));
    connect(model, SIGNAL(beforeInsert(QSqlRecord &)),
            this, SLOT(beforeInsert(QSqlRecord &)));
    connect(model,SIGNAL(beforeDelete(int)),this,SLOT(beforeDelete()));
}

void InsertDataWidget::connectModel()
{
	model->setTable(table);
	model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    listView->setModel(model);
    listView->setModelColumn(1);
    QString dbName = model->database().databaseName();
    if (dbName.isNull()) dbName = "false";
    QMessageBox::information(this,model->tableName(),dbName );
}

void InsertDataWidget::addRow()
{
    int row = model->rowCount();
    model->insertRow(row);
    QModelIndex index = model->index(row, 1);
    listView->setCurrentIndex(index);
    listView->edit(index);
}

void InsertDataWidget::delRow()
{
	QModelIndex index = listView->currentIndex();
    if (!index.isValid())
        return;
    int row = listView->currentIndex().row();
    model->removeRow(row);
    listView->setRowHidden(row,true);
    hiddenRows.insert(0,row);
}

void InsertDataWidget::revert()
{
	for (int i=0;i<hiddenRows.size();++i){
		listView->setRowHidden( hiddenRows.at(i) ,false);
	}
	hiddenRows.clear();
	model->revertAll();
}

void InsertDataWidget::submit()
{
	model->submitAll();
}

void InsertDataWidget::refresh()
{
	model->select();
}

void InsertDataWidget::beforeInsert(QSqlRecord &record)
{
    record.setValue("id", generateId(table));
    modified = true;
}

void InsertDataWidget::beforeDelete()
{
	modified = true;
}
